package com.ruoyi.training.service.impl;

import java.lang.reflect.Field;
import java.util.*;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.examination.domain.ExamRecord;
import com.ruoyi.examination.domain.ExamRecordSpecial;
import com.ruoyi.examination.mapper.ExamRecordMapper;
import com.ruoyi.examination.mapper.ExamRecordSpecialMapper;
import com.ruoyi.training.domain.*;
import com.ruoyi.training.dto.*;
import com.ruoyi.training.dto.registration.RegistrationDto;
import com.ruoyi.training.dto.registration.RegistrationImport;
import com.ruoyi.training.mapper.*;
import com.ruoyi.training.service.IStudentsService;
import com.ruoyi.training.service.ITrainingClassService;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.GroupPersonVo;
import com.ruoyi.training.vo.TrainClassVo;
import com.ruoyi.training.vo.registration.RegistrationGroupVo;
import com.ruoyi.training.vo.registration.RegistrationSubmitVo;
import com.ruoyi.training.vo.registration.RegistrationVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.service.IRegistrationService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 报名Service业务层处理
 *
 * @author hcc
 * @date 2025-09-17
 */
@Service
public class RegistrationServiceImpl implements IRegistrationService
{
    private static final Logger log = LoggerFactory.getLogger(RegistrationServiceImpl.class);
    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private UnitsMapper unitsMapper;

    @Autowired
    private ProjectsMapper projectsMapper;

    @Autowired
    private RemarksMapper remarksMapper;

    @Autowired
    private CertificateIssueMapper certificateIssueMapper;

    @Autowired
    private SpecialCertificateMapper specialCertificateMapper;

    @Autowired
    private ClassStudentMapper classStudentMapper;

    @Autowired
    private TrainingClassMapper trainingClassMapper;

    @Autowired
    private ITrainingClassService trainingClassService;

    @Autowired
    private ExamScheduleMapper examScheduleMapper;

    @Autowired
    private ExamRecordMapper examRecordMapper;

    @Autowired
    private ExamRecordSpecialMapper examRecordSpecialMapper;

    IStudentsService iStudentsService = SpringUtils.getBean(IStudentsService.class);
    /**
     * 查询报名
     *
     * @param registrationId 报名主键
     * @return 报名
     */
    @Override
    public RegistrationDto selectRegistrationByRegistrationId(String registrationId)
    {
        RegistrationDto registrationDto = registrationMapper.selectRegistrationByRegistrationId(registrationId);
        SpecialCertificate specialCertificate = specialCertificateMapper.selectSpecialCertificateByRegistrationId(registrationDto.getRegistrationId());
        if (specialCertificate != null){
            registrationDto.setOriginalAuthorityAddress(specialCertificate.getOriginalAuthorityAddress());
            registrationDto.setOriginalAuthority(specialCertificate.getOriginalAuthority());
            registrationDto.setOriginalCertificateNo(specialCertificate.getOriginalCertificateNo());
            registrationDto.setFirstIssueDate(specialCertificate.getFirstIssueDate());
            registrationDto.setExpireDate(specialCertificate.getExpireDate());
        }
        return registrationDto;
    }

    /**
     * 查询报名列表
     *
     * @param registration 报名
     * @return 报名
     */
    @Override
    public List<Registration> selectRegistrationList(Registration registration)
    {
        return registrationMapper.selectRegistrationList(registration);
    }

    /**
     * 新增报名
     *
     * @param registration 报名
     * @return 结果
     */
    @Override
    public int insertRegistration(Registration registration)
    {
        registration.setCreateTime(DateUtils.getNowDate());
        return registrationMapper.insertRegistration(registration);
    }

    /**
     * 修改报名
     *
     * @param registration 报名
     * @return 结果
     */
    @Override
    public int updateRegistration(Registration registration)
    {
        registration.setUpdateTime(DateUtils.getNowDate());
        return registrationMapper.updateRegistration(registration);
    }

    /**
     * 批量删除报名
     *
     * @param registrationIds 需要删除的报名主键
     * @return 结果
     */
    @Override
    public int deleteRegistrationByRegistrationIds(String[] registrationIds)
    {
        return registrationMapper.deleteRegistrationByRegistrationIds(registrationIds);
    }

    /**
     * 删除报名信息
     *
     * @param registrationId 报名主键
     * @return 结果
     */
    @Override
    public int deleteRegistrationByRegistrationId(String registrationId)
    {
        return registrationMapper.deleteRegistrationByRegistrationId(registrationId);
    }

    /**
     * 查询报名列表
     *
     * @param registrationVo 报名
     * @return 报名集合
     */
    @Override
    public List<RegistrationDto> selectList(RegistrationVo registrationVo) {
        List<RegistrationDto> registrationDtoList = registrationMapper.selectList(registrationVo);
        return registrationDtoList;
    }

    /**
     * 新增报名
     *
     * @param registrationSubmitVo 报名
     * @return 结果
     */
    @Override
    public int addRegistration(RegistrationSubmitVo registrationSubmitVo) {
        Registration registration = new Registration();
        BeanUtils.copyProperties(registrationSubmitVo,registration);
        Students students = new Students();
        Units unit = new Units();
        // 查询添加单位信息
        if (StringUtils.isNotEmpty(registrationSubmitVo.getUnitName()))
        {
            Units units = unitsMapper.selectUnitsByUnitName(registrationSubmitVo.getUnitName());
            if (StringUtils.isNull(units))
            {
                BeanUtils.copyProperties(registrationSubmitVo,unit);
                unit.setUnitId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                unit.setCreateTime(DateUtils.getNowDate());
                unitsMapper.insertUnits(unit);
                registration.setUnitId(unit.getUnitId());
                students.setUnitId(unit.getUnitId());
            }else {
                BeanUtils.copyProperties(registrationSubmitVo,unit);
                if (hasUpdates(unit, units, unitString)){
                    unit.setUnitId(units.getUnitId());
                    unit.setCreateTime(units.getCreateTime());
                    unit.setUpdateTime(DateUtils.getNowDate());
                    unitsMapper.updateUnits(unit);
                }
                registration.setUnitId(units.getUnitId());
            }
        }
        // 学员修改
        BeanUtils.copyProperties(registrationSubmitVo,students);
        Students studentsDb = studentsMapper.checkUserIdNumber(registrationSubmitVo.getIdNumber());
        if (StringUtils.isNull(studentsDb))
        {
            int i = iStudentsService.insertStudentsWithUser(students);
            if (i > 0){
                Students studentsByIdNumber = studentsMapper.checkUserIdNumber(registrationSubmitVo.getIdNumber());
                registration.setStudentId(studentsByIdNumber.getStudentId());
            }

        }else {
            if (hasUpdates(students,studentsDb,studentString)){
                students.setStudentId(studentsDb.getStudentId());
                iStudentsService.updateStudentsWithUser(students);
            }
            registration.setStudentId(studentsDb.getStudentId());
        }

        // 添加项目信息
        Projects projects = projectsMapper.selectProjectsByProjectId(registrationSubmitVo.getProjectId());
        if (StringUtils.isNotNull(projects))
        {
            registration.setProjectId(projects.getProjectId());
            registration.setProjectMap(projects.getExampleOne());
        }
        registration.setRegistrationId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
        registration.setProjectId(registrationSubmitVo.getProjectId());
        registration.setAgreementStatus("false");
        registration.setClassStatus("0");
        registration.setPaymentStatus("5");
        registration.setRecordStatus("0");
        registration.setSubmitStatus("0");
        registration.setDelFlag("0");
        if ("".equals(registrationSubmitVo.getWorkResume())){
            registration.setWorkResume(registrationSubmitVo.getWorkResume());
        }

        registration.setCreateTime(DateUtils.getNowDate());
        registration.setCreateBy(SecurityUtils.getUsername());
        // 判断是否是换证报名
        if ("3".equals(registrationSubmitVo.getTrainingType())){
            Projects projectsSpecial = projectsMapper.selectProjectsByName("特种设备");
            Projects projectsType = projectsMapper.selectProjectsByProjectId(projects.getpId());
            boolean contains = projects.getAncestors().contains(projectsSpecial.getProjectId());
            if (!contains){
                CertificateIssue certificateIssue = new CertificateIssue();
                // 查询发证信息
                CertificateIssue certificateIssueDb = certificateIssueMapper.getByStudentIdAndProjectId(registration.getStudentId(),registration.getProjectId());
                if (StringUtils.isNotNull(certificateIssueDb)){
                    certificateIssue.setOriginalCertificateNo(certificateIssueDb.getCertificateNo());
                    certificateIssue.setOriginalValidityStart(certificateIssueDb.getValidityStart());
                    certificateIssue.setOriginalValidityEnd(certificateIssueDb.getValidityEnd());
                }
                certificateIssue.setCertificateIssueId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                certificateIssue.setCreateBy(SecurityUtils.getUsername());
                certificateIssue.setCreateTime(DateUtils.getNowDate());
                certificateIssue.setRegistrationId(registration.getRegistrationId());
                certificateIssue.setProjectId(registration.getProjectId());
                certificateIssue.setStudentId(registration.getStudentId());
                certificateIssue.setCertificateType("2");  // 设置证书类型为复审换证
                certificateIssue.setDigitalStatus("3"); // 设置证书状态为待发
                certificateIssue.setPaperStatus("3");  // 设置证书状态为待发
                certificateIssueMapper.insertCertificateIssue(certificateIssue);
            }else {
                SpecialCertificate specialCertificate = new SpecialCertificate();
                BeanUtils.copyProperties(registrationSubmitVo,specialCertificate);
                specialCertificate.setCertificateType("2");
                specialCertificate.setRegistrationId(registration.getRegistrationId());
                specialCertificate.setStudentId(registration.getStudentId());
                specialCertificate.setProjectId(registration.getProjectId());
                specialCertificate.setWorkCategory(projectsType.getProjectName());
                specialCertificate.setWorkProject(projects.getProjectName());
                specialCertificate.setSpecialCertificateId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                specialCertificateMapper.insertSpecialCertificate(specialCertificate);
            }
        }
        return registrationMapper.insertRegistration(registration);
    }

    /**
     * 修改报名
     *
     * @param registrationSubmitVo 报名
     * @return 结果
     */
    @Override
    public int update(RegistrationSubmitVo registrationSubmitVo) {
        Registration registration = new Registration();
        BeanUtils.copyProperties(registrationSubmitVo,registration);
        Units units = new Units();
        Students students = new Students();
        // 单位修改
        if (StringUtils.isNotEmpty(registrationSubmitVo.getUnitName()))
        {
            BeanUtils.copyProperties(registrationSubmitVo,units);
            Units unitsDb = unitsMapper.selectUnitsByUnitName(registrationSubmitVo.getUnitName());
            if (StringUtils.isNull(unitsDb))
            {
                units.setUnitId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                units.setCreateTime(DateUtils.getNowDate());
                units.setUnitName(units.getUnitName());
                registration.setUnitId(units.getUnitId());
                unitsMapper.insertUnits(units);
            }else {
                if (hasUpdates(units, unitsDb, unitString)){
                    units.setUnitId(unitsDb.getUnitId());
                    units.setCreateTime(unitsDb.getCreateTime());
                    units.setUpdateTime(DateUtils.getNowDate());
                    unitsMapper.updateUnits(units);
                }
                registration.setUnitId(unitsDb.getUnitId());
            }
        }
        // 学员修改
        BeanUtils.copyProperties(registrationSubmitVo,students);
        Students studentsDb = studentsMapper.checkUserIdNumber(registrationSubmitVo.getIdNumber());
        if (StringUtils.isNull(studentsDb))
        {
            iStudentsService.insertStudentsWithUser(students);
            Students studentsByIdNumber = studentsMapper.checkUserIdNumber(registrationSubmitVo.getIdNumber());
            registration.setStudentId(studentsByIdNumber.getStudentId());
        }else {
            if (hasUpdates(students,studentsDb,studentString)){
                students.setStudentId(studentsDb.getStudentId());
                students.setUpdateTime(DateUtils.getNowDate());
                students.setUpdateBy(SecurityUtils.getUsername());
                students.setUnitId(registration.getUnitId());
                iStudentsService.updateStudentsWithUser(students);
            }
            registration.setStudentId(studentsDb.getStudentId());
        }
        // 添加项目信息
        Projects projects = projectsMapper.selectProjectsByProjectId(registrationSubmitVo.getProjectId());
        if (StringUtils.isNotNull(projects))
        {
            registration.setProjectId(projects.getProjectId());
            registration.setProjectMap(projects.getExampleOne());
        }
        registration.setUpdateTime(DateUtils.getNowDate());
        // 判断是否为复审
        if ("3".equals(registrationSubmitVo.getTrainingType())){
            // 获取特设证书信息
            SpecialCertificate specialCertificate = specialCertificateMapper.selectSpecialCertificateByRegistrationId(registration.getRegistrationId());
            if (specialCertificate != null){
                specialCertificate.setOriginalAuthorityAddress(registrationSubmitVo.getOriginalAuthorityAddress());
                specialCertificate.setOriginalCertificateNo(registrationSubmitVo.getOriginalCertificateNo());
                specialCertificate.setFirstIssueDate(registrationSubmitVo.getFirstIssueDate());
                specialCertificate.setExpireDate(registrationSubmitVo.getExpireDate());
                specialCertificate.setUpdateTime(DateUtils.getNowDate());
                specialCertificate.setUpdateBy(SecurityUtils.getUsername());
                specialCertificateMapper.updateSpecialCertificate(specialCertificate);
            }
            // 经营性证书信息
            CertificateIssue certificateIssue = certificateIssueMapper.selectCertificateIssueByRegistrationId(registration.getRegistrationId());
            if (certificateIssue != null){
                certificateIssue.setOriginalCertificateNo(registrationSubmitVo.getOriginalCertificateNo());
                certificateIssue.setOriginalValidityEnd(registrationSubmitVo.getExpireDate());
                certificateIssue.setOriginalValidityStart(registrationSubmitVo.getFirstIssuanceDate());
                certificateIssue.setUpdatedTime(DateUtils.getNowDate());
                certificateIssue.setUpdatedBy(SecurityUtils.getUsername());
                certificateIssueMapper.updateCertificateIssue(certificateIssue);
            }
        }
        return registrationMapper.updateRegistration(registration);
    }
    /**
     * 逻辑删除报名
     */
    @Override
    public int removeRegistrationByRegistrationIds(String[] registrationIds) {
        return registrationMapper.removeRegistrationByRegistrationIds(registrationIds);
    }
    /**
     * 导入报名信息
     * @param registrationImportList
     * @param updateSupport
     * @param operName
     * @return
     */
    @Override
    public String importRegistration(List<RegistrationImport> registrationImportList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(registrationImportList) || registrationImportList.size() == 0){
            throw new ServiceException("导入报名信息不能为空");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RegistrationImport registrationImport : registrationImportList) {
            try {
                Registration registration = new Registration();
                // 导入单位信息
                Units unit = new Units();
                Students students = new Students();
                if (StringUtils.isNotEmpty(registrationImport.getUnitName())){
                    BeanUtils.copyProperties(registrationImport,unit);
                    Units units = unitsMapper.selectUnitsByUnitName(registrationImport.getUnitName());
                    if (StringUtils.isNull(units))
                    {
                        unit.setUnitId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        unit.setCreateTime(DateUtils.getNowDate());
                        unit.setCreateBy(SecurityUtils.getUsername());
                        unitsMapper.insertUnits(unit);
                        registration.setUnitId(unit.getUnitId());
                    }else {
                        if (hasUpdates(unit,units,unitImportString)){
                            unit.setUnitId(units.getUnitId());
                            unit.setCreateTime(units.getCreateTime());
                            unit.setUpdateTime(DateUtils.getNowDate());
                            unitsMapper.updateUnits(unit);
                        }
                        registration.setUnitId(units.getUnitId());
                    }
                }
                String certTypeDisplay = registrationImport.getDocumentType();
                if (StringUtils.isEmpty(certTypeDisplay)) {
                    throw new ServiceException("证件类型不能为空");
                }
                String documentType = CERT_TYPE_MAP.get(certTypeDisplay.trim());
                String educationDisplay = registrationImport.getQualification(); // 导入的显示值（如“本科”）
                if (StringUtils.isEmpty(educationDisplay)) {
                    throw new ServiceException("学历不能为空");
                }
                String qualification = EDUCATION_MAP.get(educationDisplay.trim());
                // 导入学员信息
                BeanUtils.copyProperties(registrationImport,students);
                Students studentsDb = studentsMapper.checkUserIdNumber(registrationImport.getIdNumber());
                if (StringUtils.isNull(studentsDb)){
                    iStudentsService.insertStudentsWithUser(students);
                    Students studentsByIdNumber = studentsMapper.checkUserIdNumber(registrationImport.getIdNumber());
                    registration.setStudentId(studentsByIdNumber.getStudentId());
                }else {
                    if (hasUpdates(students,studentsDb,studentString)){
                        students.setStudentId(studentsDb.getStudentId());
                        students.setUpdateTime(DateUtils.getNowDate());
                        students.setDocumentType(documentType);
                        students.setQualification(qualification);
                        students.setUpdateBy(SecurityUtils.getUsername());
                        students.setUnitId(registration.getUnitId());
                        iStudentsService.updateStudentsWithUser(students);
                    }
                    registration.setStudentId(studentsDb.getStudentId());
                }

                // 导入项目信息
                Projects projects = projectsMapper.selectProjectsByName(registrationImport.getProjectName());
                if (StringUtils.isNotNull(projects)){
                    registration.setProjectId(projects.getProjectId());
                    registration.setProjectMap(projects.getExampleOne());
                }
                String trainTypeDisplay = registrationImport.getTrainingType(); // 导入的显示值（如“复审”）
                if (StringUtils.isEmpty(trainTypeDisplay)) {
                    throw new ServiceException("培训类别不能为空");
                }
                String trainingType = TRAIN_TYPE_MAP.get(trainTypeDisplay.trim());
                registration.setRegistrationId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                registration.setAgreementStatus("false");
                registration.setClassStatus("0");
                registration.setPaymentStatus("5");
                registration.setRecordStatus("0");
                registration.setSubmitStatus("0");
                registration.setDelFlag("0");
                registration.setTrainingType(trainingType);
                if ("".equals(registrationImport.getWorkResume())){
                    registration.setWorkResume(registrationImport.getWorkResume());
                }
                if ("".equals(registrationImport.getFirstIssuanceDate())){
                    registration.setFirstIssuanceDate(registrationImport.getFirstIssuanceDate());
                }
                if ("".equals(registrationImport.getCertificateCode())){
                    registration.setCertificateCode(registrationImport.getCertificateCode());
                }
                if ("".equals(registrationImport.getCertificateValidityPeriod())){
                    registration.setCertificateValidityPeriod(registrationImport.getCertificateValidityPeriod());
                }
                registration.setCreateTime(DateUtils.getNowDate());
                registration.setCreateBy(SecurityUtils.getUsername());
                registrationMapper.insertRegistration(registration);
                // 判断培训类别是否为复审
                if ("3".equals(trainingType)){
                    Projects projectsSpecial = projectsMapper.selectProjectsByName("特种设备");
                    Projects projectsType = projectsMapper.selectProjectsByProjectId(projects.getpId());
                    boolean contains = projects.getAncestors().contains(projectsSpecial.getProjectId());
                    if (!contains){
                        CertificateIssue certificateIssue = new CertificateIssue();
                        // 查询发证信息
                        CertificateIssue certificateIssueDb = certificateIssueMapper.getByStudentIdAndProjectId(registration.getStudentId(),registration.getProjectId());
                        if (StringUtils.isNotNull(certificateIssueDb)){
                            certificateIssue.setOriginalCertificateNo(certificateIssueDb.getCertificateNo());
                            certificateIssue.setOriginalValidityStart(certificateIssueDb.getValidityStart());
                            certificateIssue.setOriginalValidityEnd(certificateIssueDb.getValidityEnd());
                        }
                        certificateIssue.setCertificateIssueId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        certificateIssue.setCreateBy(SecurityUtils.getUsername());
                        certificateIssue.setCreateTime(DateUtils.getNowDate());
                        certificateIssue.setRegistrationId(registration.getRegistrationId());
                        certificateIssue.setProjectId(registration.getProjectId());
                        certificateIssue.setStudentId(registration.getStudentId());
                        certificateIssue.setCertificateType("2");  // 设置证书类型为复审换证
                        certificateIssue.setDigitalStatus("3"); // 设置证书状态为待发
                        certificateIssue.setPaperStatus("3");  // 设置证书状态为待发
                        certificateIssueMapper.insertCertificateIssue(certificateIssue);
                    }else {
                        SpecialCertificate specialCertificate = new SpecialCertificate();
                        BeanUtils.copyProperties(registrationImport,specialCertificate);
                        specialCertificate.setCertificateType("2");
                        specialCertificate.setRegistrationId(registration.getRegistrationId());
                        specialCertificate.setStudentId(registration.getStudentId());
                        specialCertificate.setProjectId(registration.getProjectId());
                        specialCertificate.setWorkCategory(projectsType.getProjectName());
                        specialCertificate.setWorkProject(projects.getProjectName());
                        specialCertificate.setSpecialCertificateId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        specialCertificateMapper.insertSpecialCertificate(specialCertificate);
                    }
                }
                successNum++;
                successMsg.append("<br/>" + successNum + "、账号 " + registrationImport.getStudentName() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + registrationImport.getStudentName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增集体报名
     */
    @Override
    public int addRegistrationGroup(RegistrationGroupVo registrationGroupVo) {
        String unitId = "";
        int i = 0;
        // 查询添加单位信息
        if (StringUtils.isNotEmpty(registrationGroupVo.getUnitInfo().getUnitName()))
        {
            Units units = unitsMapper.selectUnitsByUnitName(registrationGroupVo.getUnitInfo().getUnitName());
            if (StringUtils.isNull(units))
            {
                Units unitInfo = registrationGroupVo.getUnitInfo();
                unitInfo.setUnitId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                unitInfo.setCreateTime(DateUtils.getNowDate());
                unitsMapper.insertUnits(unitInfo);
                unitId = unitInfo.getUnitId();
            }else {
                Units unitsNew = new Units();
                BeanUtils.copyProperties(registrationGroupVo.getUnitInfo(),unitsNew);
                if (hasUpdates(unitsNew,units,unitString)){
                    unitsNew.setUnitId(registrationGroupVo.getUnitInfo().getUnitId());
                    unitsNew.setCreateTime(registrationGroupVo.getUnitInfo().getCreateTime());
                    unitsNew.setUpdateTime(DateUtils.getNowDate());
                    unitsMapper.updateUnits(unitsNew);
                }
                unitId = units.getUnitId();
            }
        }
        for (GroupPersonVo groupPersonVo : registrationGroupVo.getPersonList()) {
            Registration registration = new Registration();
            Students studentNew = new Students();
            // 学员新增
            BeanUtils.copyProperties(groupPersonVo,studentNew);
            Students studentsDb = studentsMapper.checkUserIdNumber(groupPersonVo.getIdNumber());
            if (StringUtils.isNull(studentsDb))
            {
                iStudentsService.insertStudentsWithUser(groupPersonVo);
                Students studentsByIdNumber = studentsMapper.checkUserIdNumber(groupPersonVo.getIdNumber());
                registration.setStudentId(studentsByIdNumber.getStudentId());
            }else {
                if (hasUpdates(groupPersonVo,studentsDb,studentString)){
                    groupPersonVo.setStudentId(studentsDb.getStudentId());
                    groupPersonVo.setUpdateTime(DateUtils.getNowDate());
                    groupPersonVo.setUpdateBy(SecurityUtils.getUsername());
                    groupPersonVo.setUnitId(unitId);
                    iStudentsService.updateStudentsWithUser(groupPersonVo);
                }
                registration.setStudentId(studentsDb.getStudentId());
            }
            // 添加项目信息
            Projects projects = projectsMapper.selectProjectsByProjectId(groupPersonVo.getProjectId());
            if (StringUtils.isNotNull(projects))
            {
                registration.setProjectId(projects.getProjectId());
                registration.setProjectMap(projects.getExampleOne());
            }
            registration.setRegistrationId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
            registration.setProjectId(groupPersonVo.getProjectId());
            registration.setAgreementStatus("false");
            registration.setClassStatus("0");
            registration.setPaymentStatus("5");
            registration.setRecordStatus("0");
            registration.setSubmitStatus("0");
            registration.setDelFlag("0");
            if ("".equals(groupPersonVo.getWorkReResume())){
                registration.setWorkResume(groupPersonVo.getWorkReResume());
            }
            registration.setCreateTime(DateUtils.getNowDate());
            registration.setCreateBy(SecurityUtils.getUsername());
            registration.setUnitId(unitId);
            if ("3".equals(groupPersonVo.getTrainingType())){
                Projects projectsSpecial = projectsMapper.selectProjectsByName("特种设备");
                Projects projectsType = projectsMapper.selectProjectsByProjectId(projects.getpId());
                boolean contains = projects.getAncestors().contains(projectsSpecial.getProjectId());
                if (!contains){
                    CertificateIssue certificateIssue = new CertificateIssue();
                    // 查询发证信息
                    CertificateIssue certificateIssueDb = certificateIssueMapper.getByStudentIdAndProjectId(registration.getStudentId(),registration.getProjectId());
                    if (StringUtils.isNotNull(certificateIssueDb)){
                        certificateIssue.setOriginalCertificateNo(certificateIssueDb.getCertificateNo());
                        certificateIssue.setOriginalValidityStart(certificateIssueDb.getValidityStart());
                        certificateIssue.setOriginalValidityEnd(certificateIssueDb.getValidityEnd());
                    }
                    certificateIssue.setCertificateIssueId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    certificateIssue.setCreateBy(SecurityUtils.getUsername());
                    certificateIssue.setCreateTime(DateUtils.getNowDate());
                    certificateIssue.setRegistrationId(registration.getRegistrationId());
                    certificateIssue.setProjectId(registration.getProjectId());
                    certificateIssue.setStudentId(registration.getStudentId());
                    certificateIssue.setCertificateType("2");  // 设置证书类型为复审换证
                    certificateIssue.setDigitalStatus("3"); // 设置证书状态为待发
                    certificateIssue.setPaperStatus("3");  // 设置证书状态为待发
                    certificateIssueMapper.insertCertificateIssue(certificateIssue);
                }else {
                    SpecialCertificate specialCertificate = new SpecialCertificate();
                    BeanUtils.copyProperties(groupPersonVo,specialCertificate);
                    specialCertificate.setCertificateType("2");
                    specialCertificate.setRegistrationId(registration.getRegistrationId());
                    specialCertificate.setStudentId(registration.getStudentId());
                    specialCertificate.setProjectId(registration.getProjectId());
                    specialCertificate.setWorkCategory(projectsType.getProjectName());
                    specialCertificate.setWorkProject(projects.getProjectName());
                    specialCertificate.setSpecialCertificateId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                    specialCertificateMapper.insertSpecialCertificate(specialCertificate);
                }
            }
            i = registrationMapper.insertRegistration(registration);
        }
        return i;
    }
    /**
     * 查询报名数据通过ids
     * @param registrationIds
     * @return
     */
    @Override
    public List<ApplicationFormData> selectRegistrationByIds(String[] registrationIds) {
        return registrationMapper.selectRegistrationByIds(registrationIds);
    }

    /**
     * 查询培训进度
     * lqx
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<TrainingProgress> selectListTrainingProgress(String studentId) {
        List<TrainingProgress> trainingProgressList = new ArrayList<>();
        //1.报名进度
        //1.1通过学员id去报名表中查出复合要求的报名信息。
        RegistrationVo registrationVo = new RegistrationVo();
        registrationVo.setStudentId(studentId);
        List<RegistrationDto> registrationDtoList = registrationMapper.selectList(registrationVo);
        if (!registrationDtoList.isEmpty()) {
            for (RegistrationDto registrationDto : registrationDtoList) {
                TrainingProgress trainingProgress = new TrainingProgress();
                RegistrationProgress registrationProgress = new RegistrationProgress();
                //1.2查询出报名信息，赋值报名进度为已报名
                registrationProgress.setRegistrationStatus("0");
                registrationProgress.setRegistrationDto(registrationDto);
                //1.3赋值培训进度中的报名进度
                trainingProgress.setRegistrationProgress(registrationProgress);

                //2.培训进度
                //2.1通过报名id去班级学员表中查询
                ClassStudent classStudent = classStudentMapper.selectClassStudentsByRegistrationId(registrationDto.getRegistrationId());
                ClassStudentProgress classStudentProgress = new ClassStudentProgress();
                ExamProgress examProgress = new ExamProgress();
                CertificateProgress certificateProgress = new CertificateProgress();
                if (classStudent != null) {
                    //2.2.1不为空，则通过班级id去班级表中查询班级状态
//                    TrainingClass trainingClass = trainingClassMapper.selectTrainingClassByTrainingClassId(classStudent.getTrainingClassId());
                    TrainClassVo trainClassVo = trainingClassService.selectTrainingClassVoByTrainingClassId(classStudent.getTrainingClassId());
                    //2.2.1.1将班级状态赋值为培训进度状态
                    //class_status（字典：1-未开班，2-已开班，3-已结束），若1则为待培训，若2则为培训中，若3则为培训已结束
                    classStudentProgress.setClassStudentStatus(trainClassVo.getClassStatus());
                    //2.2.1.2赋值班级学员数据
                    classStudentProgress.setClassStudent(classStudent);
                    //2.2.1.3赋值班级数据
//                    classStudentProgress.setTrainingClass(trainingClass);
                    classStudentProgress.setTrainClassVo(trainClassVo);
                    //2.3赋值培训进度中的培训进度
                    trainingProgress.setClassStudentProgress(classStudentProgress);

                    //3.考试进度
                    //3.1通过报名id查询班级学员表，参考2.1
                    //3.2不为空，则班级学员表中对应的考试状态赋值为考试进度状态
                    //考试状态(0-未排考，1-已排考，2-已考试)
                    //考试进度0-未排考，1-已排考，2-已考完
                    examProgress.setExamStatus(classStudent.getExamStatus());
                    //3.3.1若为未排考，则不进行下一步的查询操作
                    if ("0".equals(examProgress.getExamStatus())) {
                        trainingProgress.setExamProgress(examProgress);
//                    certificateProgress.setCertificateStatus("0");
//                    trainingProgress.setCertificateProgress(certificateProgress);
                    }
                    //3.3.2若为已排考，执行查询操作
                    if ("1".equals(examProgress.getExamStatus())) {
                        //3.3.2.1查询考试安排
                        if (!"".equals(classStudent.getExamScheduleId()) && classStudent.getExamScheduleId() != null) {
                            ExamSchedule examSchedule = examScheduleMapper.selectExamScheduleByExamScheduleId(classStudent.getExamScheduleId());
                            if (examSchedule != null) {
                                examProgress.setExamSchedule(examSchedule);
                                trainingProgress.setExamProgress(examProgress);
                            }
                        }
//                    certificateProgress.setCertificateStatus("0");
//                    trainingProgress.setCertificateProgress(certificateProgress);
                    }
                    //3.3.3若为已考试，执行查询操作
                    if ("2".equals(examProgress.getExamStatus())) {
                        //3.3.3.1查询考试安排
                        if (!"".equals(classStudent.getExamScheduleId()) && classStudent.getExamScheduleId() != null) {
                            ExamSchedule examSchedule = examScheduleMapper.selectExamScheduleByExamScheduleId(classStudent.getExamScheduleId());
                            if (examSchedule != null) {
                                examProgress.setExamSchedule(examSchedule);
                                trainingProgress.setExamProgress(examProgress);
                            }
                        }
                        //3.3.3.2查询考试成绩
                        //3.3.3.2.1查询经营性考试成绩
                        List<ExamRecord> examRecordInfo = examRecordMapper.getExamRecordInfoById(classStudent.getTrainingClassId(), studentId, classStudent.getProjectId());
                        if (!examRecordInfo.isEmpty()) {
                            examProgress.setExamRecordList(examRecordInfo);
                            trainingProgress.setExamProgress(examProgress);
                        } else {//3.3.3.2.2查询特设考试成绩
                            ExamRecordSpecial examRecordSpecial = new ExamRecordSpecial();
                            examRecordSpecial.setStudentId(studentId);
                            List<ExamRecordSpecial> examRecordSpecials = examRecordSpecialMapper.selectExamRecordSpecialList(examRecordSpecial);
                            if (!examRecordSpecials.isEmpty()) {
                                examProgress.setExamRecordSpecialList(examRecordSpecials);
                                trainingProgress.setExamProgress(examProgress);
                            }
                        }
                    }
                    //4.证书进度
                    //4.1通过报名id去经营性证书表和特设证书表中查询
                    //4.1.1查询经营性证书
                    CertificateIssue certificateIssue = certificateIssueMapper.selectCertificateIssueByRegistrationId(registrationDto.getRegistrationId());
                    if (certificateIssue != null) {
                        certificateProgress.setCertificateIssue(certificateIssue);
                        certificateProgress.setCertificateStatus("1");
                        trainingProgress.setCertificateProgress(certificateProgress);
                    } else {//查询特设证书
                        SpecialCertificate specialCertificate = specialCertificateMapper.selectSpecialCertificateByRegistrationId(registrationDto.getRegistrationId());
                        if (specialCertificate != null) {
                            certificateProgress.setSpecialCertificate(specialCertificate);
                            certificateProgress.setCertificateStatus("1");
                            trainingProgress.setCertificateProgress(certificateProgress);
                        } else {
                            certificateProgress.setCertificateStatus("0");
                            trainingProgress.setCertificateProgress(certificateProgress);
                        }
                    }
                } else {
                    //2.2.1为空，则设置培训、考试、证书状态为对应状态
                    //培训状态 1-待培训，2-培训中，3-培训已结束
                    classStudentProgress.setClassStudentStatus("1");
                    //考试进度0-未排考，1-已排考，2-已考完
                    examProgress.setExamStatus("0");
                    //证书状态0-未发放 1-已发放
                    certificateProgress.setCertificateStatus("0");
                    //赋值培训进度中的培训进度
                    trainingProgress.setClassStudentProgress(classStudentProgress);
                    //赋值培训进度中的考试进度
                    trainingProgress.setExamProgress(examProgress);
                    //赋值培训进度中的证书进度
                    trainingProgress.setCertificateProgress(certificateProgress);
                }
                //将每个报名对应的进度赋值
                trainingProgressList.add(trainingProgress);
            }
        }
        return trainingProgressList;
    }

    /**
     * 个人报名列表
     */
    @Override
    public List<RegistrationDto> personRegistrationList(RegistrationVo registrationVo) {
        registrationVo.setStudentId(SecurityUtils.getLoginUser().getSysUser().getStudentId());
        List<RegistrationDto> registrationDtoList = registrationMapper.selectList(registrationVo);
        return registrationDtoList;
    }

    /**
     * 比较两个对象，只检查指定集合中的字段
     */
    private boolean hasUpdates(Object source, Object target, Set<String> fields) {
        for (String fieldName : fields) {
            try {
                // 获取字段并设置可访问
                Field field = source.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);

                // 获取两个对象的字段值
                Object newValue = field.get(source);
                Object oldValue = field.get(target);

                // 处理两个值都为null的情况
                if (newValue == null && oldValue == null) {
                    continue; // 两者均为null，视为相等，继续检查下一个字段
                }
                // 处理其中一个为null的情况
                if (newValue == null || oldValue == null) {
                    return true; // 一个为null另一个非null，说明有更新
                }
                // 两个均非null，使用equals比较
                if (!newValue.equals(oldValue)) {
                    return true;
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                continue;
            }
        }
        return false;
    }

    private static final Set<String> unitString = new HashSet<>();
    static {
        unitString.add("unitName");
        unitString.add("socialCreditCode");
        unitString.add("administrativeArea");
        unitString.add("unitNature");
        unitString.add("contact");
        unitString.add("unitPhonenumber");
    }

    private static final Set<String> studentString = new HashSet<>();
    static {
        studentString.add("studentName");
        studentString.add("phonenumber");
        studentString.add("certificateStarttime");
        studentString.add("certificateEndtime");
        studentString.add("userType");
        studentString.add("certificateType");
        studentString.add("sex");
        studentString.add("birthDate");
        studentString.add("nation");
        studentString.add("position");
        studentString.add("qualification");
        studentString.add("graduatedFrom");
        studentString.add("major");
        studentString.add("address");
        studentString.add("email");
        studentString.add("fax");
        studentString.add("postCode");
        studentString.add("idNumber");
    }
    private static final Set<String> unitImportString = new HashSet<>();
    static {
        unitImportString.add("unitName");
        unitImportString.add("unitAddress");
        unitImportString.add("contact");
        unitImportString.add("unitPhonenumber");
    }

    private static final Set<String> studentImportString = new HashSet<>();
    static {
        studentImportString.add("studentName");
        studentImportString.add("phonenumber");
        studentImportString.add("certificateType");
        studentImportString.add("idNumber");
        studentImportString.add("qualification");
        studentImportString.add("address");
        studentImportString.add("postCode");
    }

    // 新增：定义字典常量（显示值→编码映射，根据实际业务填写正确的键值对）
    private static final Map<String, String> CERT_TYPE_MAP; // 证件类型：显示值→编码
    private static final Map<String, String> TRAIN_TYPE_MAP; // 培训类别：显示值→编码
    private static final Map<String, String> EDUCATION_MAP; // 学历：显示值→编码

    // 初始化字典常量（根据实际业务填充，以下为示例）
    static {
        // 证件类型：key=显示值（如Excel中填写的内容），value=数据库存储的编码
        CERT_TYPE_MAP = new HashMap<>();
        CERT_TYPE_MAP.put("身份证", "IDCARD");
        CERT_TYPE_MAP.put("士官证", "SGCARD");
        CERT_TYPE_MAP.put("士兵证", "SBCARD");
        CERT_TYPE_MAP.put("其他证件", "OTCARD");

        // 培训类别：key=显示值，value=编码（示例中“复审”对应编码“3”，与后续判断一致）
        TRAIN_TYPE_MAP = new HashMap<>();
        TRAIN_TYPE_MAP.put("新训", "1");
        TRAIN_TYPE_MAP.put("复训", "2");
        TRAIN_TYPE_MAP.put("复审", "3");
        TRAIN_TYPE_MAP.put("二次考试", "4");

        // 学历：key=显示值，value=编码
        EDUCATION_MAP = new HashMap<>();
        EDUCATION_MAP.put("初中", "CZ");
        EDUCATION_MAP.put("高中", "GZ");
        EDUCATION_MAP.put("中专", "ZZ");
        EDUCATION_MAP.put("大专", "DZ");
        EDUCATION_MAP.put("本科", "BK");
        EDUCATION_MAP.put("硕士研究生", "CSYJS");
        EDUCATION_MAP.put("博士研究生", "BSYJS");
    }
}
